
package com.ziyun.pop.modules.storeMember.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.service.common.constant.AppType;
import com.service.ucenter.api.UserLoginService;
import com.service.ucenter.constant.UcenterResult;
import com.service.ucenter.model.login.RegisterParamDto;
import com.ziyun.pop.common.e.order.BillTypeEnum;
import com.ziyun.pop.common.e.order.PayObjectEnum;
import com.ziyun.pop.common.e.order.PayTypeEnum;
import com.ziyun.pop.common.utils.EnumUtil;
import com.ziyun.pop.common.utils.MD5;
import com.ziyun.pop.common.utils.UserUtils;
import com.ziyun.pop.modules.erpUserLog.entity.ErpUserLogEntity;
import com.ziyun.pop.modules.erpUserLog.service.ErpUserLogService;
import com.ziyun.pop.modules.order.entity.UserPaymentEntity;
import com.ziyun.pop.modules.order.utils.UserPaymentUtils;
import com.ziyun.pop.modules.remittance.entity.RemittanceEntity;
import com.ziyun.pop.modules.remittance.service.RemittanceService;
import com.ziyun.pop.modules.storeFavouredPrice.entity.StoreFavouredPriceEntity;
import com.ziyun.pop.modules.storeFavouredPrice.service.StoreFavouredPriceService;
import com.ziyun.pop.modules.storeMember.dao.StoreMemberDao;
import com.ziyun.pop.modules.storeMember.entity.*;
import com.ziyun.pop.modules.storeMember.service.StoreMemberService;
import com.ziyun.pop.modules.storeMember.service.UserBaseInfoService;
import com.ziyun.pop.modules.storeMember.vo.StoreMemberEntityVo;
import com.ziyun.pop.modules.userAdvance.entity.UserAdvanceEntity;
import com.ziyun.pop.modules.userAdvance.service.UserAdvanceService;
import com.ziyun.pop.modules.supp.entity.SellerInfoEntity;
import com.ziyun.pop.modules.supp.service.SellerInfoService;
import com.ziyun.pop.modules.userPayment.service.UserPaymentService;
import com.ziyun.pop.modules.userPaymentBill.entity.UserPaymentBillEntity;
import com.ziyun.pop.modules.userPaymentBill.service.UserPaymentBillService;
import io.renren.common.exception.RRException;
import io.renren.common.utils.DateUtils;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.common.utils.R;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service("storeMemberService")
public class StoreMemberServiceImpl extends ServiceImpl<StoreMemberDao, StoreMemberEntity> implements StoreMemberService {

    @Autowired
    private StoreMemberDao storeMemberDao;
    @Autowired
    private UserLoginService userLoginServicel;
    @Autowired
    private UserBaseInfoService userBaseInfoService;
    @Autowired
    private StoreFavouredPriceService storeFavouredPriceService;
    @Autowired
    private UserAdvanceService userAdvanceService;
    @Autowired
    private ErpUserLogService erpUserLogService;
    @Autowired
    private RemittanceService remittanceService;
    @Autowired
    private SellerInfoService sellerInfoService;
    @Autowired
    private UserPaymentService userPaymentService;
    @Autowired
    private UserPaymentBillService userPaymentBillService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Page<StoreMemberEntity> page = (Page<StoreMemberEntity>) this.page(
                new Query<StoreMemberEntity>(params).getPage(),
                new QueryWrapper<StoreMemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public R list(Map<String, Object> params) {
        Page<StoreMemberVO> page = new Page<>();
        page.setCurrent(Integer.valueOf(params.get("page").toString()));
        page.setSize(Integer.valueOf(params.get("limit").toString()));
        List<StoreMemberVO> list = storeMemberDao.list(page, params);
        page.setRecords(list);
        PageUtils pageUtils = new PageUtils(page);
        // 存放枚举类到userdata
        Map<String, List> mapEnum = new HashMap<>();
        //根据seller_id查询该门店的业务员
        List<Map<Long, String>> sellernames = storeMemberDao.getUsernames(Integer.valueOf(params.get("sellerId").toString()));
        //查询当前商户的全部账套信息
        List<StoreFavouredPriceEntity> storeFavouredPriceEntityList = storeFavouredPriceService.list(new QueryWrapper<StoreFavouredPriceEntity>().eq("seller_id",Integer.valueOf(params.get("sellerId").toString())));
        mapEnum.put("sellernames", sellernames);
        //查询近5天新增人数
        Integer allCount=this.baseMapper.getCountIn5(Integer.valueOf(params.get("sellerId").toString()));
        int mallCount = this.baseMapper.getCountIn5Mall(Integer.valueOf(params.get("sellerId").toString()));
        int twbCount = this.baseMapper.getCountIn5Twb(Integer.valueOf(params.get("sellerId").toString()));
        return R.ok().put("page", pageUtils).put("userData", mapEnum).put("storeFavouredPriceEntityList",storeFavouredPriceEntityList).put("allCount",allCount).put("mallCount",mallCount).put("twbCount",twbCount);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R insertStoreMember(StoreMemberEntity storeMember) {
        //手机号码不为空
        if (StringUtils.isNotBlank(storeMember.getMobile())) {
            //分别根据用户名和手机号查询
            List<UserBaseInfoEntity> nameList = userBaseInfoService.list(new QueryWrapper<UserBaseInfoEntity>().eq("name", storeMember.getName()));
            List<UserBaseInfoEntity> mobileList = userBaseInfoService.list(new QueryWrapper<UserBaseInfoEntity>().eq("mobile", storeMember.getMobile()));
            if (nameList.size() >= 1 && mobileList.size() >= 1) {
                return R.error("该会员名和手机号在user_base_info分别被注册");
            }
            if (nameList.size() > 1) {
                return R.error("会员名在user_base_info存在2个以上");
            }
            if (mobileList.size() > 1) {
                return R.error("手机号在user_base_info存在2个以上");
            }
            if (nameList.size() == 1) {
                //在store_member表添加用户
                return this.insertStoreMember(storeMember, nameList);
            } else if (mobileList.size() == 1) {
                //在store_member表添加用户
                return this.insertStoreMember(storeMember, mobileList);
            } else {
                //调用接口注册用户
                return this.remoteRegister(storeMember);
            }

        } else {
            List<UserBaseInfoEntity> list = userBaseInfoService.list(new QueryWrapper<UserBaseInfoEntity>().eq("name", storeMember.getName()));
            if (list.size() > 1) {
                return R.error("会员名在user_base_info存在2个以上");
            } else if (list.size() == 1) {
                //在store_member表添加用户
                return this.insertStoreMember(storeMember, list);

            } else {//userbaseinfo表也不存在,就调用接口注册
                //调用接口注册用户
                return this.remoteRegister(storeMember);
            }
        }
    }

    @Override
    public R getOneById(Long sid) {
        StoreMemberVO storeMemberVO = storeMemberDao.getOneById(sid);
        return R.ok().put("storeMemberVO", storeMemberVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R addAdvance(Integer memberId, BigDecimal advance,String payWay) {
        //更新用户预存款
        Integer result = storeMemberDao.addAdvance(memberId, advance);
        if (result < 1) {
            return R.error("未找到用户信息!");
        }

        BigDecimal count=advance;
        //查询当前预存款
        BigDecimal nowAdvance = storeMemberDao.getAdvance(memberId);

        //预存款流水表
        UserAdvanceEntity userAdvanceEntity = new UserAdvanceEntity();
        userAdvanceEntity.setUserId(memberId);
        userAdvanceEntity.setMemberAdvance(nowAdvance);
        userAdvanceEntity.setMoney(count);
        userAdvanceEntity.setMessage("pop预存款充值");
        userAdvanceEntity.setImportMoney(count);
        userAdvanceEntity.setPaymethod(payWay);
        userAdvanceEntity.setCreateName(UserUtils.getCurentUser().getUsername());
        userAdvanceEntity.setMtime(new Date());
        userAdvanceService.save(userAdvanceEntity);
        //日志表
        ErpUserLogEntity erpUserLogEntity = new ErpUserLogEntity();
        erpUserLogEntity.setUserId(memberId);
        erpUserLogEntity.setCreateBy(UserUtils.getCurentUser().getUsername());
        erpUserLogEntity.setLog("POP系统充值:会员ID(" + memberId + ")预存款增加" + count);
        erpUserLogService.save(erpUserLogEntity);
        return R.ok();
    }

    @Override
    public void cancel(Long sid) {
        storeMemberDao.cancel(sid);
    }

    @Override
    public R twbsave(StoreMemberEntity storeMember) {
        //判断用户名是否存在
        Integer count = this.baseMapper.selectCount(new QueryWrapper<StoreMemberEntity>().eq("name", storeMember.getName()).eq("seller_id",storeMember.getSellerId()));
        if (count > 0) {
            return R.error("会员名称已存在!");
        }
        storeMember.setMemberId(0);
        storeMember.setMerchantsSource(1);
        this.baseMapper.insert(storeMember);
        return R.ok();
    }



    //调用接口注册用户
    private R remoteRegister(StoreMemberEntity storeMember) {
        //组装参数
        Integer referralsCode = storeMemberDao.getReferralsCode(storeMember.getSellerId());
        RegisterParamDto registerParamDto = new RegisterParamDto();
        registerParamDto.setUserType(2);
        registerParamDto.setAccount(storeMember.getName());
        registerParamDto.setPhone(storeMember.getMobile());
        registerParamDto.setPassword(MD5.getMD5Code("000000"));
        registerParamDto.setRegisterSource("pop");
        registerParamDto.setReferralsCode(Long.valueOf(referralsCode));
        //调用接口
        UcenterResult<com.service.common.model.UserInfo> result = userLoginServicel.registerByErp(AppType.erp, registerParamDto);
        if (result != null && result.getCode() == UcenterResult.success().getCode()) {
            com.service.common.model.UserInfo userInfo = result.getData();
            storeMember.setMemberId(userInfo.getUserId().intValue());
            storeMember.setMerchantsType("register");
            Integer count = this.baseMapper.insert(storeMember);
            if (count > 0) {
                return R.ok();
            }
        }
        return R.error(result.getMessage());
    }

    //在store_member表添加用户
    private R insertStoreMember(StoreMemberEntity storeMember, List<UserBaseInfoEntity> list) {
        UserBaseInfoEntity entity = list.get(0);
        //根据用户名在user_base_info查到唯一的一个,在store_member插入数据
        storeMember.setMemberId(entity.getUserId());//设置用户id
        storeMember.setMerchantsType("visit");//设置来访类型
        storeMember.setCreateTime(new Date());
        storeMemberDao.insert(storeMember);
        return R.ok();
    }

    //图文宝查询客户
    @Override
    public R getMemberByName(Map<String, Object> params) {

       List<StoreMemberEntityVo> storeMemberData=this.baseMapper.getMemberByName(params);
        return R.ok().put("storeMemberData",storeMemberData);
    }

    @Override
    public StoreMemberEntityVo getMemberBySId(Map<String, Object> params) {
        List<StoreMemberEntityVo> list = this.baseMapper.getMemberByName(params);
        if(list.size()>0){
            return list.get(0);
        }
        return null;
    }

    @Override
    public R customer(Map<String,Object> params) {
        Page<Customer> page = new Page<>();
        page.setCurrent(Integer.valueOf(params.get("page").toString()));
        page.setSize(Integer.valueOf(params.get("limit").toString()));
        List<Customer> list = this.baseMapper.customer(page,params);
        page.setRecords(list);
        PageUtils pageUtils = new PageUtils(page);

        return R.apiOk(pageUtils);
    }

    @Override
    public R customerManager(Integer sellerId) {
        CustomerManager customerManager=new CustomerManager();
        //复购客户
        Integer repeatBuy = this.baseMapper.repeatBuy(sellerId);
        customerManager.setRepeatBuy(repeatBuy);
        //客户分析
        List<CustomerWeek> customerWeeks = this.baseMapper.customerWeek(sellerId);
        customerManager.setCustomerWeeks(customerWeeks);
        //昨日新增
        customerManager.setYesterdayAdd(customerWeeks.get(customerWeeks.size()-2).getCount());
        //在线下单
        Integer onlineCount = this.baseMapper.onlineCount(sellerId);
        customerManager.setOnlineCount(onlineCount);
        //到店客户
        Integer offlineCount = this.baseMapper.offlineCount(sellerId);
        customerManager.setOfflineCount(offlineCount);
        //总客户
        customerManager.setTotal(onlineCount+offlineCount);
        return R.apiOk(customerManager);
    }

    public int repeatBuy(Integer sellerId){
        return this.baseMapper.repeatBuy(sellerId);
    }

    public int onlineCount(Integer sellerId){
        return this.baseMapper.onlineCount(sellerId);
    }

    public int offlineCount(Integer sellerId){
        return this.baseMapper.offlineCount(sellerId);
    }

    @Override
    public int onlineNewCount(Integer sellerId) {
        return this.baseMapper.onlineNewCount(sellerId);
    }

    @Override
    public int offlineNewCount(Integer sellerId) {
        return this.baseMapper.offlineNewCount(sellerId);
    }

    /**
     * 扫码支付开始
     * @param params
     * @return
     */
    @Override
    @Transactional
    public R sweepCodeBegin(Map<String, Object> params) {
        BigDecimal money = new BigDecimal(params.get("advance").toString());
        String memberId = params.get("memberId").toString();
        //添加支付单信息
        UserPaymentEntity userPayment = new UserPaymentEntity();
        // 收款单号
        String paymentId = null;
        // 判断收款单号是否重复
        boolean repeat = true;
        do {
            paymentId = UserPaymentUtils.getPaymentsId();
            List<UserPaymentEntity> countList = userPaymentService.list(new QueryWrapper<UserPaymentEntity>().eq("payment_id", paymentId));
            if (countList == null || countList.size() <= 0) {
                repeat = false;
            }
        } while (repeat);

        userPayment.setPaymentId(paymentId);
        userPayment.setMoney(money);
        userPayment.setCurMoney(money);
        userPayment.setUserId(memberId);
        userPayment.setStatus("ready");
        userPayment.setPayName(PayTypeEnum.SWEEPCODE.name());
        userPayment.setTPayed(new Date());
        userPayment.setPayType("online");
        userPayment.setTBegin(new Date());
        userPayment.setPayAppId(PayTypeEnum.SWEEPCODE.toCode());
        //用户支付记录表;
        userPaymentService.save(userPayment);
        // 订单，支付单关联信息
        UserPaymentBillEntity userPaymentBill = new UserPaymentBillEntity();
        userPaymentBill.setRelId(Long.valueOf(memberId));
        userPaymentBill.setBillId(userPayment.getPaymentId());
        userPaymentBill.setPayObject(PayObjectEnum.RECHARGE.toCode());
        userPaymentBill.setBillType(BillTypeEnum.PAYMENTS.toCode());
        userPaymentBill.setMoney(userPayment.getMoney());
        userPaymentBillService.save(userPaymentBill);

        // 返回 支付金额 分， 支付流水 右侧补空格 长度50位

        // 拼接银联请求字符串
        StringBuffer sBuffer = new StringBuffer("02"); //应用类型  02-无硬件POS通
        sBuffer.append("0000000000000000");// POS机号 + 员工号
        sBuffer.append("00");//交易类型  00－消费
        sBuffer.append(String.format("%012d", money.multiply(BigDecimal.valueOf(100L)).intValue())); // 金额 无小数点"."，单位为分，不足时12位左补0
        sBuffer.append(DateUtils.format(new Date(), "yyyyMMdd"));// 交易日期 YYYMMDD
        sBuffer.append("000000000000");//原交易参考号
        sBuffer.append("000000");//凭证号
        sBuffer.append("ERP");//LRC校验
        //sBuffer.append(params.get("serialCode"));
        sBuffer.append(String.format("%1$-50s",params.get("serialCode"))); // 串码
        sBuffer.append(String.format("%1$-50s",paymentId));// 商户订单号


        return R.ok().put("DUmsocx1",sBuffer).put("paymentId",paymentId);
    }

    @Override
    @Transactional
    public R sweepCodeCallBack(Map<String, Object> params) {
        // 先处理支付订单信息,将支付状态改为成功
        String paymentId = params.get("paymentId").toString();
        String sweepCodeData = params.get("sweepCodeData").toString();
        UserPaymentEntity userPaymentEntity = userPaymentService.getById(paymentId);
        if (userPaymentEntity == null){
            throw new RRException("支付单号异常!");
        }

        //先写入响应码
        userPaymentEntity.setPayResponseData(sweepCodeData);
        userPaymentService.writePayResponseData(userPaymentEntity);

    /*    //转换字符串格式
        String sweepCodeDataGbk= null;
        try {
            sweepCodeDataGbk  =  new String(sweepCodeData.getBytes(),"gbk");
        } catch (UnsupportedEncodingException e) {
            throw new RRException("响应结果转GBK 异常!");
        }*/
        // 截取 回调状态
        if(!sweepCodeData.substring(0,2).equals("00")){
            throw new RRException("支付失败!响应码为:"+sweepCodeData);
        }

       /* // 截取支付方式
        String payType= sweepCodeDataGbk.substring(506,507);

        String payCode = null;
        String payName = null;
        if (payType.equals("0")){
            payCode = "sweepcodealipay";
            payName = "扫码支付宝";
        }else if (payType.equals("1")){
            payCode = "sweepcodeweixin";
            payName = "扫码微信";
        }else if (payType.equals("2")){
            payCode = "sweepcodeunion";
            payName = "扫码银联";
        }else if (payType.equals("3")){
            payCode = "sweepcodeother";
            payName = "扫码其它";
        }else {
            throw new RRException("获取支付方式异常!");
        }*/

        userPaymentEntity.setStatus("succ");
        userPaymentEntity.setTPayed(new Date());
        //userPaymentEntity.setPayAppId(payCode);
        userPaymentService.updateById(userPaymentEntity);
        // 处理业务信息 Integer memberId, BigDecimal advance,String payWay
        Integer userId = Integer.valueOf(userPaymentEntity.getUserId());
        BigDecimal count = userPaymentEntity.getMoney();
        R r = this.addAdvanceSweep(userId, count, paymentId);
        return r;
    }

    @Override
    public R logicDelete(List<Long> sids) {
        this.baseMapper.logicDelete(sids);
        return R.ok();
    }

    @Override
    public R bindBankCard(RemittanceEntity remittanceEntity) {
        if (remittanceEntity.getId() == null) {
            //新增
            SellerInfoEntity sellerInfoEntity = sellerInfoService.getOne(new QueryWrapper<SellerInfoEntity>().eq("seller_id", remittanceEntity.getSellerId().intValue()));
            remittanceEntity.setMerchantType(Integer.valueOf(sellerInfoEntity.getSellerType()));
            remittanceEntity.setCredentialType(1);
            remittanceEntity.setReceiverBankAccountPro("0");
            remittanceEntity.setCurrency("人民币");
            remittanceEntity.setPaymentType("快速");
            remittanceEntity.setBusinessType("普通汇兑");
            remittanceEntity.setExpectDay("20080808");
            remittanceEntity.setExpectTime("0800");
            remittanceEntity.setPaymentBranch("武汉雄楚金地城支行");
            remittanceService.save(remittanceEntity);
        }else {
            //修改
            remittanceService.updateById(remittanceEntity);
        }
        return R.ok();
    }


    private R addAdvanceSweep(Integer memberId, BigDecimal advance,String paymentId) {
        //更新用户预存款
        Integer result = storeMemberDao.addAdvance(memberId, advance);
        if (result < 1) {
            return R.error("未找到用户信息!");
        }

        BigDecimal count=advance;
        //查询当前预存款
        BigDecimal nowAdvance = storeMemberDao.getAdvance(memberId);

        //预存款流水表
        UserAdvanceEntity userAdvanceEntity = new UserAdvanceEntity();
        userAdvanceEntity.setUserId(memberId);
        userAdvanceEntity.setMemberAdvance(nowAdvance);
        userAdvanceEntity.setMoney(count);
        userAdvanceEntity.setMessage("pop预存款充值");
        userAdvanceEntity.setPaymentId(paymentId);
        userAdvanceEntity.setImportMoney(count);
        userAdvanceEntity.setPaymethod("扫码支付");
        userAdvanceEntity.setCreateName(UserUtils.getCurentUser().getUsername());
        userAdvanceEntity.setMtime(new Date());
        userAdvanceService.save(userAdvanceEntity);
        //日志表
        ErpUserLogEntity erpUserLogEntity = new ErpUserLogEntity();
        erpUserLogEntity.setUserId(memberId);
        erpUserLogEntity.setCreateBy(UserUtils.getCurentUser().getUsername());
        erpUserLogEntity.setLog("POP系统充值:会员ID(" + memberId + ")预存款增加" + count);
        erpUserLogService.save(erpUserLogEntity);
        return R.ok();
    }

}

